import React, { useState, useEffect } from 'react';
import {Table, Button, Modal, Form, Input, TreeSelect, InputNumber, message, Card, Descriptions, Space, Popconfirm, Select} from 'antd';
import {SearchOutlined, EditOutlined, DeleteOutlined, PlusOutlined, FileExcelOutlined,} from '@ant-design/icons';
import * as XLSX from 'xlsx';


const { TextArea } = Input;

const SupplierManagement = () => {
    const [suppliers, setSuppliers] = useState([]);
    const [filteredSuppliers, setFilteredSuppliers] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [currentSupplier, setCurrentSupplier] = useState(null);
    const [searchText, setSearchText] = useState('');
    const [form] = Form.useForm();
    const [addForm] = Form.useForm();
    const [filterType, setFilterType] = useState(null);

    const [isPurchaseModalVisible, setIsPurchaseModalVisible] = useState(false);
    const [supplierPurchases, setSupplierPurchases] = useState([]);
    const [editingSupplier, setEditingSupplier] = useState(null);
    // 模拟目录树数据
    const categoryTreeData = [
        {
            title: '建筑材料',
            key: 1,
            value: 1,
            children: [
                { title: '钢筋', key: 2, value: 2 },
                {
                    title: '水泥',
                    key: 3,
                    value: 3,
                    children: [
                        { title: '建筑水泥', key: 6, value: 6 },
                        { title: '家用水泥', key: 7, value: 7 },
                    ],
                },
            ],
        },
        {
            title: '五金材料',
            key: 8,
            value: 8,
            children: [
                { title: '螺丝', key: 9, value: 9 },
                { title: '螺帽', key: 10, value: 10 },
            ],
        },
    ];

    const mockPurchaseList = [
        {
            id: 1,
            subtotal: 141950.00,
            numbering: 'PO2023001',
            supplier: 1,
            name: '商品混凝土',
            specification: 'C30',
            quantity: 300,
            unit: '立方米',
            unitPrice: 450,
            rate: 0.05,
            other_fee: 200,
            remark: '快递费200',
            status: 5,
            purchaseTime: '2023-03-10',
            paymentTime: '2023-03-11',
        },
        {
            id: 2,
            subtotal: 32000.00,
            numbering: 'PO2023001',
            supplier: 2,
            name: '钢筋',
            specification: 'HRB400',
            quantity: 10,
            unit: '吨',
            unitPrice: 3200,
            rate: 0.05,
            other_fee: 0,
            remark: '',
            status: 1,
            purchaseTime: '2023-03-12',
            paymentTime: '',
        }
    ];

    const statusMean = {
        1: '审核中',
        2: '未付款',
        3: '已取消',
        4: '已完成',
        5: '已付款'
    };

    // 辅助函数：通过 key 查找对应的分类名称
    const findTitleByKey = (data, key) => {
        for (let node of data) {
            if (node.key === key) return node.title;
            if (node.children) {
                const found = findTitleByKey(node.children, key);
                if (found) return found;
            }
        }
        return '';
    };

    // 模拟初始数据
    useEffect(() => {
        const mockData = [
            {
                id: 1,
                name: 'ABC 电子有限公司',
                type: 6,
                level: 3,
                tax_number: '123456789012345',
                legal_person: '张三',
                legal_phone: '13800138001',
                contact_person: '李四',
                contact_phone: '13800138002',
                bank_account: '中国银行 1234 5678 9012 3456',
                address: '北京市海淀区科技园路1号',
                remarks: '长期合作供应商，信誉良好'
            },
            {
                id: 2,
                name: 'XYZ 材料供应商',
                type: 7,
                level: 2,
                tax_number: '987654321098765',
                legal_person: '王五',
                legal_phone: '13800138003',
                contact_person: '赵六',
                contact_phone: '13800138004',
                bank_account: '工商银行 9876 5432 1098 7654',
                address: '上海市浦东新区工业区88号',
                remarks: '价格有优势，交货准时'
            }
        ];
        setSuppliers(mockData);
        setFilteredSuppliers(mockData);
    }, []);

    // 搜索功能
    const handleSearch = (value, type) => {
        setSearchText(value);
        setFilterType(type);

        let filtered = suppliers;

        // 按名称过滤
        if (value) {
            filtered = filtered.filter(supplier =>
                supplier.name.toLowerCase().includes(value.toLowerCase())
            );
        }

        // 按类型过滤（type 不为 null 时才过滤）
        if (type != null) {
            filtered = filtered.filter(supplier => supplier.type === type);
        }

        setFilteredSuppliers(filtered);
    };

    // 打开采购列表模态框
    const showPurchaseModal = (supplier) => {
        setEditingSupplier(supplier);
        const relatedPurchases = mockPurchaseList.filter(p => p.supplier === supplier.id);
        setSupplierPurchases(relatedPurchases);
        setIsPurchaseModalVisible(true);
    };
    const handleStatusChange = (id, newStatus) => {
        setSupplierPurchases(prev =>
            prev.map(item => item.id === id ? { ...item, status: newStatus } : item)
        );
        message.success('状态已更新');
    };

    // 打开新增模态框
    const showAddModal = () => {
        addForm.resetFields();
        setIsAddModalVisible(true);
    };

    // 打开编辑模态框
    const showEditModal = (supplier) => {
        setCurrentSupplier(supplier);
        form.setFieldsValue(supplier);
        setIsModalVisible(true);
    };

    // 打开详情模态框
    const showDetailModal = (supplier) => {
        setCurrentSupplier(supplier);
        setIsDetailModalVisible(true);
    };

    // 保存新增供应商
    const handleAdd = () => {
        addForm.validateFields().then(values => {
            // 生成新ID (实际项目中应该由后端生成)
            const newId = suppliers.length > 0 ? Math.max(...suppliers.map(s => s.id)) + 1 : 1;

            const newSupplier = {
                id: newId,
                ...values
            };

            const updatedSuppliers = [...suppliers, newSupplier];
            setSuppliers(updatedSuppliers);
            setFilteredSuppliers(updatedSuppliers);
            setIsAddModalVisible(false);
            message.success('供应商添加成功');
        }).catch(error => {
            console.error('Validation failed:', error);
        });
    };

    // 保存修改
    const handleSave = () => {
        form.validateFields().then(values => {
            const updatedSuppliers = suppliers.map(supplier =>
                supplier.id === currentSupplier.id ? { ...supplier, ...values } : supplier
            );

            setSuppliers(updatedSuppliers);
            setFilteredSuppliers(updatedSuppliers);
            setIsModalVisible(false);
            message.success('供应商信息更新成功');
        }).catch(error => {
            console.error('Validation failed:', error);
        });
    };

    // 删除供应商
    const handleDelete = (id) => {
        try {
            const updatedSuppliers = suppliers.filter(supplier => supplier.id !== id);
            setSuppliers(updatedSuppliers);
            setFilteredSuppliers(updatedSuppliers);
            message.success('供应商删除成功');
        } catch (error) {
            console.error('删除失败:', error);
            message.error('删除失败');
        }
    };

    // 导出Excel
    const exportToExcel = () => {
        const worksheet = XLSX.utils.json_to_sheet(filteredSuppliers.map(supplier => ({
            'ID': supplier.id,
            '供应商名称': supplier.name,
            '类型': findTitleByKey(categoryTreeData, supplier.type),
            '等级': supplier.level,
            '税号': supplier.tax_number,
            '法人代表': supplier.legal_person,
            '法人电话': supplier.legal_phone,
            '联系人': supplier.contact_person,
            '联系电话': supplier.contact_phone,
            '银行账号': supplier.bank_account,
            '地址': supplier.address,
            '备注': supplier.remarks
        })));

        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "供应商列表");

        // 获取当前日期用于文件名
        const today = new Date();
        const dateStr = `${today.getFullYear()}${(today.getMonth()+1).toString().padStart(2, '0')}${today.getDate().toString().padStart(2, '0')}`;

        XLSX.writeFile(workbook, `供应商列表_${dateStr}.xlsx`);
    };

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80,
            sorter: (a, b) => a.id - b.id,
        },
        {
            title: '供应商名称',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <a onClick={() => showDetailModal(record)}>{text}</a>
            ),
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (type) => findTitleByKey(categoryTreeData, type),
        },
        {
            title: '等级',
            width: 80,
            dataIndex: 'level',
            key: 'level',
        },
        {
            title: '备注',
            dataIndex: 'remarks',
            key: 'remarks',
            ellipsis: true,
        },
        {
            title: '操作',
            key: 'action',
            width: 240,
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => showEditModal(record)}
                    />
                    <Popconfirm
                        title="确定要删除此供应商吗?"
                        onConfirm={() => handleDelete(record.id)}
                        okText="是"
                        cancelText="否"
                    >
                        <Button
                            type="link"
                            danger
                            icon={<DeleteOutlined />}
                        />
                    </Popconfirm>
                    <Button
                        type="link"
                        onClick={() => showPurchaseModal(record)}
                    >
                        查看采购材料
                    </Button>
                </Space>
            ),
        }
    ];

    return (
        <div style={{ padding: 24 }}>
            <Card
                title="供应商管理"
                extra={
                    <Space>
                        <Input.Search
                            placeholder="搜索供应商名称"
                            allowClear
                            enterButton={<SearchOutlined />}
                            // size="large"
                            value={searchText}
                            onChange={(e) => handleSearch(e.target.value)}
                            onSearch={(val) => handleSearch(val)}
                            style={{ width: 300 }}
                        />
                        {/* 类型筛选 */}
                        <TreeSelect
                            style={{ width: 200 }}
                            treeData={categoryTreeData}
                            placeholder="筛选类型"
                            allowClear
                            treeDefaultExpandAll
                            value={filterType}
                            onChange={(val) => handleSearch(searchText, val)}
                        />
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={showAddModal}
                        >
                            新增供应商
                        </Button>
                        <Button 
                            type="default" 
                            icon={<FileExcelOutlined />} 
                            onClick={exportToExcel}
                        >
                            导出Excel
                        </Button>
                    </Space>
                }
            >
                <Table
                    columns={columns}
                    dataSource={filteredSuppliers}
                    rowKey="id"
                    bordered
                    pagination={{ pageSize: 10 }}
                />
            </Card>

            {/* 编辑模态框 */}
            <Modal
                title="编辑供应商信息"
                open={isModalVisible}
                onOk={handleSave}
                onCancel={() => setIsModalVisible(false)}
                width={800}
                destroyOnHidden={ true}
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={currentSupplier}
                >
                    <Form.Item
                        label="供应商名称"
                        name="name"
                        rules={[{ required: true, message: '请输入供应商名称' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="类型"
                        name="type"
                        rules={[{ required: true, message: '请选择类型' }]}
                    >
                        <TreeSelect
                            treeData={categoryTreeData}
                            placeholder="请选择类型"
                            treeDefaultExpandAll
                        />
                    </Form.Item>

                    <Form.Item
                        label="等级"
                        name="level"
                        rules={[{ required: true, message: '请输入等级' }]}
                    >
                        <InputNumber style={{ width: '100%' }} min={1} />
                    </Form.Item>

                    <Form.Item
                        label="税号"
                        name="tax_number"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="法人代表"
                        name="legal_person"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="法人电话"
                        name="legal_phone"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="联系人"
                        name="contact_person"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="联系电话"
                        name="contact_phone"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="银行账号"
                        name="bank_account"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="地址"
                        name="address"
                    >
                        <TextArea rows={2} />
                    </Form.Item>

                    <Form.Item
                        label="备注"
                        name="remarks"
                    >
                        <TextArea rows={3} />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 新增供应商模态框 */}
            <Modal
                title="新增供应商"
                open={isAddModalVisible}
                onOk={handleAdd}
                onCancel={() => setIsAddModalVisible(false)}
                width={800}
                destroyOnHidden={ true}
            >
                <Form
                    form={addForm}
                    layout="vertical"
                >
                    <Form.Item
                        label="供应商名称"
                        name="name"
                        rules={[{ required: true, message: '请输入供应商名称' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="类型"
                        name="type"
                        rules={[{ required: true, message: '请选择类型' }]}
                    >
                        <TreeSelect
                            treeData={categoryTreeData}
                            placeholder="请选择类型"
                            treeDefaultExpandAll
                        />
                    </Form.Item>

                    <Form.Item
                        label="等级"
                        name="level"
                        rules={[{ required: true, message: '请输入等级' }]}
                    >
                        <InputNumber style={{ width: '100%' }} min={1} />
                    </Form.Item>

                    <Form.Item
                        label="税号"
                        name="tax_number"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="法人代表"
                        name="legal_person"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="法人电话"
                        name="legal_phone"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="联系人"
                        name="contact_person"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="联系电话"
                        name="contact_phone"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="银行账号"
                        name="bank_account"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="地址"
                        name="address"
                    >
                        <TextArea rows={2} />
                    </Form.Item>

                    <Form.Item
                        label="备注"
                        name="remarks"
                    >
                        <TextArea rows={3} />
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title={`供应商采购材料 - ${editingSupplier?.name || ''}`}
                open={isPurchaseModalVisible}
                onCancel={() => setIsPurchaseModalVisible(false)}
                footer={null}
                width={900}
            >
                <Table
                    dataSource={supplierPurchases}
                    rowKey="id"
                    bordered
                    pagination={false}
                    columns={[
                        { title: '编号', dataIndex: 'id', width: 80 },
                        { title: '材料名称', dataIndex: 'name' },
                        { title: '规格', dataIndex: 'specification' },
                        { title: '数量', dataIndex: 'quantity' },
                        { title: '单位', dataIndex: 'unit' },
                        { title: '单价', dataIndex: 'unitPrice' },
                        {
                            title: '状态',
                            dataIndex: 'status',
                            render: (status, record) => (
                                <Select
                                    value={status}
                                    onChange={(val) => handleStatusChange(record.id, val)}
                                    style={{ width: 120 }}
                                >
                                    {Object.entries(statusMean).map(([key, label]) => (
                                        <Select.Option key={key} value={Number(key)}>
                                            {label}
                                        </Select.Option>
                                    ))}
                                </Select>
                            )
                        }
                    ]}
                />
            </Modal>

            {/* 详情模态框 */}
            <Modal
                title="供应商详情"
                open={isDetailModalVisible}
                onCancel={() => setIsDetailModalVisible(false)}
                footer={[
                    <Button key="edit" type="primary" onClick={() => {
                        setIsDetailModalVisible(false);
                        showEditModal(currentSupplier);
                    }}>
                        编辑
                    </Button>,
                    <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
                        关闭
                    </Button>
                ]}
                width={800}
            >
                {currentSupplier && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="ID">{currentSupplier.id}</Descriptions.Item>
                        <Descriptions.Item label="供应商名称">{currentSupplier.name}</Descriptions.Item>
                        <Descriptions.Item label="类型">
                            {findTitleByKey(categoryTreeData, currentSupplier.type)}
                        </Descriptions.Item>
                        <Descriptions.Item label="等级">{currentSupplier.level}</Descriptions.Item>
                        <Descriptions.Item label="税号">{currentSupplier.tax_number}</Descriptions.Item>
                        <Descriptions.Item label="法人代表">{currentSupplier.legal_person}</Descriptions.Item>
                        <Descriptions.Item label="法人电话">{currentSupplier.legal_phone}</Descriptions.Item>
                        <Descriptions.Item label="联系人">{currentSupplier.contact_person}</Descriptions.Item>
                        <Descriptions.Item label="联系电话">{currentSupplier.contact_phone}</Descriptions.Item>
                        <Descriptions.Item label="银行账号" span={2}>
                            {currentSupplier.bank_account}
                        </Descriptions.Item>
                        <Descriptions.Item label="地址" span={2}>
                            {currentSupplier.address}
                        </Descriptions.Item>
                        <Descriptions.Item label="备注" span={2}>
                            {currentSupplier.remarks}
                        </Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>
        </div>
    );
};

export default SupplierManagement;
